<template>
  <van-sticky :offset-top="46">
    <van-dropdown-menu>
      <van-dropdown-item v-model="regionIndexValue" :options="regionList" @change="changeRegion" />
      <van-dropdown-item v-model="channelValue" :options="channels" @change="changeChannel" />
      <van-dropdown-item v-model="personalizationValue" :options="personalization" @change="changePersonalization" />
    </van-dropdown-menu>
  </van-sticky>

  <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" loading-text="正在加载影院列表"
    @load="loadMore">
    <!-- <van-cell v-for="cinema in cinemas" :key="cinema.cinemaId" :title="cinema.name" /> -->
    <ul class="cinema-list">
      <van-row v-for="cinema in cinemaList" :key="cinema.cinemaId" class="cinema" tag="li" :wrap="true"
        :gutter="[10, 30]" align="center" @click="jumpToCinemaDetail(cinema.cinemaId)">
        <!-- {{cinema.cinemaId}}  -->
        <van-col span="18">
          <div class="name">{{ cinema.name }}</div>
          <div class="address">{{ cinema.address }}</div>
        </van-col>
        <van-col span="6">
          <div class="lowPrice"><i>￥</i>{{ cinema.lowPrice }}起</div>
          <div class="distance">{{ cinema.Distance }} km</div>
        </van-col>
      </van-row>
    </ul>
  </van-list>
</template>



<script setup>
import { ref, onMounted, computed } from 'vue';
import { useStore } from '@/stores/index.js';
const store = useStore();
import { getCinemaList } from '@/api/index.js';
import { useRouter } from 'vue-router';
const router = useRouter();

import { filterCinemaByDistrictName, filterCinemaByTicketFlag, filterCinemaByVisited, filterCinemaByDistance } from "@/api/tool.js"



const loading = ref(false)
const finished = ref(false)



//cinemas 用于在模板显示经过筛选函数处理之后的电影院
//allCinemas 用于页面初始化的时候保存全部电影院，目的减少请求次数
//filteredCinemas 用于保存每次筛选的结果
const cinemas = ref([]) // 电影院列表
const allCinemas = ref([]) // 所有电影院列表，作为后续筛选数据源使用

const filteredCinemas = ref([]) // 当前页面剩余的电影院

const allCity = ref(true) //全城标记


const regionList = ref([])
const regionIndexValue = ref(0)

const channels = ref([{ text: "APP订票", value: 0 }, { text: "前台兑换", value: 1 }])
const channelValue = ref(0)

const personalization = ref([{ text: "最近去过", value: 0 }, { text: "离我最近", value: 1 }])
const personalizationValue = ref(0)


// 计算属性，处理 lowPrice 和 Distance 的小数点处理
const cinemaList = computed(() => {
  return cinemas.value.map(cinema => {
    return {
      ...cinema,
      lowPrice: (parseFloat(cinema.lowPrice) / 100).toFixed(1),
      Distance: parseFloat(cinema.Distance).toFixed(1)
    };
  });
});


//下拉切换行政区域
const changeRegion = async (value) => {
  regionIndexValue.value = value; // 确保 regionIndexValue 被正确设置
  if (value === 0) {
    // 全城
    cinemas.value = allCinemas.value; //用筛选后的数据显示
    filteredCinemas.value = allCinemas.value;  //更新筛选后的数据源
    allCity.value = true // 是全城
  } else {
    //其他行政区
    const selectedRegion = regionList.value.find(region => region.value === value);
    if (selectedRegion) {
      cinemas.value = filterCinemaByDistrictName(allCinemas.value, selectedRegion.text)
      filteredCinemas.value = cinemas.value
      allCity.value = false // 不是全城
    } else {
      console.error("Selected region not found");
    }
  }

  getCityRegion(allCinemas.value) // 重新获取城市行政区域
  loading.value = false;
  finished.value = true;

  console.log("点击菜单的text:", regionList.value[regionIndexValue.value].text);
  console.log("点击菜单的value:", regionList.value[regionIndexValue.value].value);
  console.log("点击菜单的index:", regionIndexValue.value);


  // getCityRegion(cinemas.value) // 重新获取城市行政区域
}

// 下拉筛选购票渠道  value:0 APP 1 前台兑换
const changeChannel = (value) => {
  if (allCity.value) { // 全城
    cinemas.value = filterCinemaByTicketFlag(allCinemas.value, value);
    filteredCinemas.value = cinemas.value;
  } else { // 其他行政区
    const selectedRegion = regionList.value.find(region => region.value === regionIndexValue.value);
    if (selectedRegion) {
      const regionFilteredCinemas = filterCinemaByDistrictName(allCinemas.value, selectedRegion.text);
      cinemas.value = filterCinemaByTicketFlag(regionFilteredCinemas, value);
      filteredCinemas.value = cinemas.value;
    } else {
      console.error("Selected region not found");
    }
  }
  loading.value = false;
  finished.value = true;
  getCityRegion(filteredCinemas.value); // 重新获取城市行政区域

};

//下拉个性化筛选
const changePersonalization = (value) => {
  if (allCity.value) {
    if (value === 0) {
      cinemas.value = filterCinemaByVisited(allCinemas.value, 1);  // 最近去过
    } else if (value === 1) {
      cinemas.value = filterCinemaByDistance(allCinemas.value);
    }
  } else {
    const selectedRegion = regionList.value.find(region => region.value === regionIndexValue.value);
    if (selectedRegion) {
      const regionFilteredCinemas = filterCinemaByDistrictName(allCinemas.value, selectedRegion.text);
      if (value === 0) {
        cinemas.value = filterCinemaByVisited(regionFilteredCinemas, 1);  // 最近去过
      } else if (value === 1) {
        cinemas.value = filterCinemaByDistance(regionFilteredCinemas);
      }
    } else {
      console.error("Selected region not found");
    }
  }
  filteredCinemas.value = cinemas.value;
  loading.value = false;
  finished.value = true;
  getCityRegion(filteredCinemas.value); // 重新获取城市行政区域
};


const loadMore = async () => {
  console.log("load  事件");
  if (finished.value) {
    loading.value = false; // 不显示loading
    // return; // 如果已经完成，不再请求
  }
}


// 获取全部电影院数据
const fetchAllCinemas = async (cityId, pageNum, pageSize) => {
  if (finished.value) {
    loading.value = false; // 不显示loading
    return; // 如果已经完成，不再请求
  }
  loading.value = true; // 显示loading
  const response = await getCinemaList(cityId, pageNum, pageSize);
  // 请求全部数据
  cinemas.value.push(...response.data.cinemas); // 保存全部电影院列表
  store.setCinemasTotal(response.data.total);
  store.setCinemas(cinemas.value);
  allCinemas.value = cinemas.value //保存全部电影院
  loading.value = false;

  if (cinemas.value.length >= store.total) {
    finished.value = true;
    return; // 如果已经获取完所有数据，则设置 finished 为 true
  } else {
    //没有加载完那么继续加载
    loading.value = true;
    store.setPageNum(store.pageNum + 1); // 跳到下一页
    if (store.pageNum <= Math.ceil(store.cinemasTotal / store.pageSize)) {
      await fetchAllCinemas(store.cityId, store.pageNum, store.pageSize);
    }
  }
}

// 获取城市行政区域
const getCityRegion = (cinemas) => {
  // 使用 map 提取 districtName，然后使用 Set 去重
  const regionSet = new Set(cinemas.map(cinema => cinema.districtName));
  // 将 Set 转换为数组
  regionList.value = Array.from(regionSet);
  regionList.value.unshift({ text: "全城", value: 0 }); // ['全城',"xxx","yyy","zzz"]
  // 构建 regions 数组
  const regions = regionList.value.map((item, index) => ({ //[{ text: "全城", value: 0 }, { text: "xxx", value: 1 }, { text: "yyy", value: 2 }, { text: "zzz", value: 3 }]
    text: item.text || item,
    value: index
  }));

  regionList.value = regions
  console.log("行政区域改变了:", regions);
  // console.log(regionList.value);
  // return regionList.value;
};


onMounted(async () => {
  // 页面默认加载全部电影院
  await fetchAllCinemas(store.cityId, store.pageNum, store.pageSize)
  // 获取城市全部行政区域 regionList
  getCityRegion(allCinemas.value) //获取城市行政区域
})

const jumpToCinemaDetail = (id) => {
  console.log("jump to detail", id);
  // 跳转去电影院详情页
  router.push({ path: `/cinema/${id}` })
};

</script>


<style scoped>
.cinema {
  padding: 15px;
  text-align: left;
  box-sizing: border-box;
  font-size: 15px;
  color: #191a1b;
  white-space: nowrap;
  border-bottom: 1px solid #ededed;
}

.cinema .name {
  width: calc(100% - 65px);
  font-size: 15px;
  color: #191a1b;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 5px;
}

.cinema .address {
  font-size: 12px;
  color: #797d82;
  width: calc(100% - 65px);
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 5px;
}

.cinema .lowPrice {
  width: 100%;
  font-size: 15px;
  color: #ff5f16;
  text-align: right;
}

.cinema .distance {
  width: 100%;
  font-size: 11px;
  text-align: right;
  /* color: #ff5f16; */
}
</style>
